package com.yanqu.road.server.manager.wingroom;

import com.alibaba.fastjson.JSON;
import com.yanqu.road.dao.impl.wingroom.CrossUserVisitRewardDataDaoImpl;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.wingroom.CrossUserVisitRewardData;
import com.yanqu.road.entity.wingroom.CrossWingRoomEventData;
import com.yanqu.road.entity.wingroom.eWingRoomEventStatus;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.wingroom.WingRoomProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ：zfr
 * @date ：2022/3/24 21:06
 */
public class CrossWingRoomMgr extends TempMgr {
    private static Map<Long, CrossWingRoomEventData> crossWingRoomEventDataMap = new ConcurrentHashMap<>();
    private static boolean isNotifySync;

    private static Map<Long, CrossUserVisitRewardData> crossUserVisitRewardDataMap = new ConcurrentHashMap<>();

    /**
     * 记录事件变化的玩家
     */
    private static Map<Long, Set<Long>> eventDataChangeMap = new ConcurrentHashMap<>();

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        crossUserVisitRewardDataMap = new CrossUserVisitRewardDataDaoImpl().getCrossUserVisitRewardData();
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        for (Map.Entry<Long, CrossUserVisitRewardData> dataEntry : crossUserVisitRewardDataMap.entrySet()) {
            CrossUserVisitRewardData rewardData = dataEntry.getValue();
            if (rewardData.isInsertOption()) {
                new CrossUserVisitRewardDataDaoImpl().add(rewardData);
            } else if (rewardData.isUpdateOption()) {
                new CrossUserVisitRewardDataDaoImpl().update(rewardData);
            }
        }
        return true;
    }

    public static void updatePatronsVisitReward(long userId, int endTime, String reward, long homeUser) {
        CrossUserVisitRewardData rewardData = crossUserVisitRewardDataMap.get(userId);
        if (rewardData == null) {
            synchronized (crossUserVisitRewardDataMap) {
                rewardData = crossUserVisitRewardDataMap.get(userId);
                if (rewardData == null) {
                    rewardData = new CrossUserVisitRewardData();
                    rewardData.setInsertOption();
                    rewardData.setUserId(userId);
                }
            }
        }
        synchronized (rewardData) {
            rewardData.setHomeUserId(homeUser);
            rewardData.setReward(reward);
            rewardData.setEndTime(endTime);
            rewardData.setGet(false);
        }
        if (rewardData.isInsertOption()) {
            crossUserVisitRewardDataMap.put(userId, rewardData);
        }
    }

    public static WingRoomProto.CrossGetVisitRewardRespMsg.Builder getVisitReward(long playerId) {
        WingRoomProto.CrossGetVisitRewardRespMsg.Builder respMsg = WingRoomProto.CrossGetVisitRewardRespMsg.newBuilder();
        CrossUserVisitRewardData rewardData = crossUserVisitRewardDataMap.get(playerId);
        if (rewardData == null) {
            return null;
        }
        synchronized (rewardData) {
            if (rewardData.isGet()) {
                return null;
            }
            rewardData.setGet(true);
            respMsg.setEndTime(rewardData.getEndTime());
            respMsg.setHomeUserId(rewardData.getHomeUserId());
            respMsg.setReward(rewardData.getReward());
            respMsg.setNickName("");
            respMsg.setHomeUserServerId(0);
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(rewardData.getHomeUserId());
            if (userBaseInfo != null) {
                respMsg.setNickName(userBaseInfo.getNickName());
                respMsg.setHomeUserServerId(userBaseInfo.getServerId());
            }
        }
        return respMsg;
    }

    public static void putEventData(WingRoomProto.SyncCrossAllEventStatusMsg syncMsg) {
        for (WingRoomProto.CrossEventStatusMsg statusMsg : syncMsg.getMsgList()) {
            if (!crossWingRoomEventDataMap.containsKey(statusMsg.getUserId())) {
                CrossWingRoomEventData data = new CrossWingRoomEventData();
                data.setUserId(statusMsg.getUserId());
                data.setStatus(statusMsg.getStatus());
                data.setBeginTime(statusMsg.getBeginTime());
                data.setGetRewardUserList(statusMsg.getGetRewardUserList());
                crossWingRoomEventDataMap.put(data.getUserId(), data);
                continue;
            }
            CrossWingRoomEventData eventData = crossWingRoomEventDataMap.get(statusMsg.getUserId());
            eventData.setStatus(statusMsg.getStatus());
            eventData.setBeginTime(statusMsg.getBeginTime());
            eventData.setGetRewardUserList(statusMsg.getGetRewardUserList());
        }
    }

    public static void notifyServerSync() {
        if (!isNotifySync) {
            for (ServerInfo serverInfo : ServerListMgr.getChannelServerList(ConfigHelper.getInt("channelId"))) {
                YanQuMessage message = YanQuMessageUtils.buildMessage(GameProtocol.S_WING_ROOM_CROSS_NOTIFY_SYNC_EVENT);
                MessageHelper.sendPacket(serverInfo.getServerId(), 0, message);
            }
            isNotifySync = true;
        }
    }

    public static boolean isDuringEventShare(long playerId, CrossWingRoomEventData userEvent) {
        if (userEvent.getStatus() < eWingRoomEventStatus.GetReward.getStatus()) {
            return false;
        }
        long nowTime = System.currentTimeMillis();
        if (nowTime - userEvent.getBeginTime() <= GameConfig.WINGROOM_FIND_FRIENDS_OTHER_PICK_UP_TIME * DateHelper.HOUR_MILLIONS) {
            return !userEvent.getGetRewardUserList().contains(playerId);
        }
        return false;
    }

    public static List<WingRoomProto.WingRoomFriendTemp.Builder> getUserEventStatus(long playerId, List<WingRoomProto.UnionMemberBaseInfoMsg> playerBaseInfoList) {
        List<WingRoomProto.WingRoomFriendTemp.Builder> list = new ArrayList<>();
        for (WingRoomProto.UnionMemberBaseInfoMsg userInfo : playerBaseInfoList) {
            CrossWingRoomEventData crossWingRoomEventData = crossWingRoomEventDataMap.get(userInfo.getUserId());
            if (crossWingRoomEventData != null) {
                WingRoomProto.WingRoomFriendTemp.Builder builder = WingRoomProto.WingRoomFriendTemp.newBuilder();
                builder.setUserId(userInfo.getUserId());
                builder.setIsRelative(false);
                if(userInfo.hasRelatives()){
                    builder.setIsRelative(true);
                }
                builder.setPlayerBaseInfo(userInfo.getPlayerBaseInfo());
                builder.setDurEvent(isDuringEventShare(playerId, crossWingRoomEventData));
                list.add(builder);
            }
        }
        return list;
    }

    public static void markUserEventDataChange(long serverId, List<Long> userList) {
        synchronized (eventDataChangeMap) {
            eventDataChangeMap.computeIfAbsent(serverId, k -> new HashSet<>());
            eventDataChangeMap.get(serverId).addAll(userList);
        }
        getLogger().debug("-------------------记录事件变更：玩家：{}", JSON.toJSONString(userList));
    }

    public static void notifyChangeToFriend() {
        Map<Long, Set<Long>> changeMap;
        synchronized (eventDataChangeMap) {
            if (eventDataChangeMap.size() == 0) {
                return;
            }
            changeMap = eventDataChangeMap;
            eventDataChangeMap = new ConcurrentHashMap<>();
        }
        for (Map.Entry<Long, Set<Long>> longSetEntry : changeMap.entrySet()) {
            WingRoomProto.UserWingRoomEventDataSyncDone.Builder builder = WingRoomProto.UserWingRoomEventDataSyncDone.newBuilder();
            long serverId = longSetEntry.getKey();
            builder.addAllUserId(longSetEntry.getValue());
            MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(Protocol.S_WING_ROOM_USER_EVENT_DATA_STATUS_SYNC_DONE, builder));
            getLogger().debug("-------------------同步事件变更：玩家：{}", JSON.toJSONString(longSetEntry.getValue()));
        }
    }

    public static WingRoomProto.CrossCalEventRedDotRespMsg.Builder calEventRedDot(long playerId, List<Long> friendList) {
        WingRoomProto.CrossCalEventRedDotRespMsg.Builder respMsg = WingRoomProto.CrossCalEventRedDotRespMsg.newBuilder();
        respMsg.setVisit(0);

        for (Long friendId : friendList) {
            CrossWingRoomEventData eventData = crossWingRoomEventDataMap.get(friendId);
            if (eventData == null) {
                continue;
            }
            if (isDuringEventShare(playerId, eventData)) {
                respMsg.setVisit(1);
                break;
            }
        }

        return respMsg;
    }

    public static Map<Long, CrossWingRoomEventData> getCrossWingRoomEventDataMap() {
        return crossWingRoomEventDataMap;
    }
}
